package com.rr.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author RR
 * @date 2021/3/27 20:38
 */
@Service
public class PaymentService {

    public String paymentInfoOK(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + ",id:" + id;
    }

    public String paymentInfoTimeout(Integer id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + ",id:" + id;
    }

    //==服务熔断==
    //断路器有  关，开，半开状态
    //当出现故障，==开==启断路器后，过了设定时间后会尝试==半开==，半开后觉得正常再==关==掉断路器
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//最近10次请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//开启断路器后10秒后尝试半开
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")//失败率超过60%后开断路器
            //这里的意思就是：在最近的10次请求里，如果调用方法失败率超过60%，开启断路器，所有请求都会
            //走服务降级的方法，在断路器开启（1000毫秒）10秒过后，尝试断路器半开，若服务调用正常，则恢复服务调用链路
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException();
        }
        return "调用成功，输入为:" + id + ",UUID:" + UUID.randomUUID();
    }
    private String paymentCircuitBreakerFallback(Integer id) {
        return "调用失败，服务降级，输入为:" + id + ",UUID:" + UUID.randomUUID();
    }
}
